package ar.uade.edu.fain.ad.client.web.servlet.caja.cierreCaja;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.uade.edu.fain.ad.client.web.servlet.caja.CajaServlet;
import ar.uade.edu.fain.ad.common.exception.PedidoPendienteException;
import ar.uade.edu.fain.ad.common.transfer.CajaVO;
import ar.uade.edu.fain.ad.common.transfer.CierreCajaVO;

/**
 * Servlet implementation class ValidacionDatosServlet
 */
public class ValidacionDatosServlet extends CajaServlet {
	private static final Integer[] DENOMINACIONES_BILLETES = 
			new Integer[] {2,5,10,20,50,100};
	private static final long serialVersionUID = 1L;

	/**
	 * @see CajaServlet#CajaServlet()
	 */
	public ValidacionDatosServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		forward(getViewBasePath() + "cierreCaja/cargarDatos.jsp", 
				request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final CajaVO cajaVO = new CajaVO();
		cajaVO.setId((Long) request.getSession().getAttribute("cajaId"));
		try {
			final CierreCajaVO cierreCajaVO = 
					getCajaDelegate().prepararCierre(cajaVO);
			popularCierreConDatos(request, cierreCajaVO);
			request.getSession().setAttribute("cierreCaja", cierreCajaVO);
			forward(getViewBasePath() + "cierreCaja/confirmarCierre.jsp", 
					request, response);
		} catch (PedidoPendienteException e) {
			request.setAttribute("pedidos", e.getPendientes());
			forward(getViewBasePath() + "cierreCaja/pedidosPedientes.jsp", 
					request, response);
		}
	}

	private void popularCierreConDatos(HttpServletRequest request,
			final CierreCajaVO cierreCajaVO) {
		for (Integer denominacion : DENOMINACIONES_BILLETES) {
			final Integer cantidadBillete = 
					Integer.valueOf(request.getParameter(
							"cantidadBillete_" + denominacion.toString()));
			cierreCajaVO.getCantidadPorBilleteEnCaja()
					.put(denominacion, cantidadBillete);
		}
		cierreCajaVO.setCantidadCuponesEnCaja(
				Integer.valueOf(request.getParameter("cantidadCupones")));
		cierreCajaVO.setTotalCuponesEnCaja(
				Double.valueOf(request.getParameter("totalCupones")));
	}

}
